package com.jms.framework.aware;

import com.jms.framework.context.ApplicationContext;
import com.jms.framework.exception.PropertyAlreadySetException;

/**
 * ApplicationContextAwareInitializer类用于初始化和提供对ApplicationContext的访问
 * 它实现了ApplicationContextAware接口，通过依赖注入的方式设置ApplicationContext
 * 此类使用单例模式确保在系统中只有一个实例，以提高性能和一致性
 */
public class  ApplicationContextAwareInitializer implements ApplicationContextAware {

    // 单例模式的实例，使用volatile关键字确保多线程环境下正确处理实例的创建
    private volatile static ApplicationContextAwareInitializer instance;

    // 静态变量，存储ApplicationContext实例
    private static ApplicationContext applicationContext;

    /**
     * 设置ApplicationContext的方法
     * 如果已经设置了ApplicationContext，则抛出PropertyAlreadySetException异常
     *
     * @param context ApplicationContext实例，用于设置初始化
     * @throws PropertyAlreadySetException 如果已经设置了ApplicationContext，则抛出此异常
     */
    @Override
    public void setApplicationContext(ApplicationContext context) {
        if (applicationContext != null) {
            throw new PropertyAlreadySetException(ApplicationContext.class, "applicationContext");
        }
        applicationContext = context;
    }

    public void initApplicationContextAware(ApplicationContextAware applicationContextAware) {
        applicationContextAware.setApplicationContext(applicationContext);
    }

    /**
     * 私有构造方法，防止外部实例化
     */
    private ApplicationContextAwareInitializer() {
    }

    /**
     * 获取ApplicationContextAwareInitializer的单例实例
     * 使用双重检查锁定（Double-Checked Locking）模式确保线程安全
     *
     * @return ApplicationContextAwareInitializer的实例
     */
    public static ApplicationContextAwareInitializer getInstance() {
        if (instance == null) {
            synchronized (ApplicationContextAwareInitializer.class) {
                if (instance == null) {
                    instance = new ApplicationContextAwareInitializer();
                }
            }
        }
        return instance;
    }
}
